package com.zhiwang.planet.ui.main

import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.zhiwang.planet.R
import com.zhiwang.planet.aop.net.NetWorkRequired
import com.zhiwang.planet.aop.util.Throttle
import com.zhiwang.planet.di.component.DaggerMainComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.*
import com.zhiwang.planet.exception.ExpiredException
import com.zhiwang.planet.mvp.p.ActivityPresenter
import com.zhiwang.planet.mvp.p.SdkPresenter
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvp.v.AvatarView
import com.zhiwang.planet.mvp.v.NickNameView
import com.zhiwang.planet.mvvm.model.entity.main.Banner
import com.zhiwang.planet.mvvm.model.entity.main.IndexData
import com.zhiwang.planet.mvvm.viewmodel.ShareViewModel
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.ui.my.*
import com.zhiwang.planet.ui.my.message.MessageCenterActivity
import com.zhiwang.planet.ui.my.record.DetailsActivity
import com.zhiwang.planet.ui.my.reward.RewardListActivity
import com.zhiwang.planet.ui.my.withdraw.WithDrawRecordActivity
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.NickNameEditorDialog
import com.zhiwang.planet.widget.SimpleDialogBuilder
import com.zhiwang.planet.widget.SimpleNetWorkLoopingPagerAdapter
import kotlinx.android.synthetic.main.fragment2_my.*
import kotlinx.android.synthetic.main.textview.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import javax.inject.Inject

@SuppressLint("LogNotTimber")
class MyFragment : BaseFragment(), View.OnClickListener, AvatarView, NickNameEditorDialog.Companion.OnPromoteListener, NickNameView, View.OnTouchListener {
    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        val e = event!!.action and MotionEvent.ACTION_MASK
        if (e == MotionEvent.ACTION_MOVE) {
            v!!.isPressed = false
            return true
        }
        return false
    }

    override fun onNickNameSet(nickName: String) {
        userPresenter.queryUserInfo()
        alertDialog.dismiss()
    }

    private val TAG = "MyFragment"

    @Inject
    lateinit var userPresenter: UserPresenter

    @Inject
    lateinit var activityPresenter: ActivityPresenter

    @Inject
    lateinit var sdkPresenter: SdkPresenter


    var phoneBind = false


    val shareVieModel by viewModels<ShareViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerMainComponent.builder()
                .appComponent(getAppComponent())
                .accountModule(AccountModule(context as AppCompatActivity))
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        EventBus.getDefault().register(this)
        userPresenter.avatarView = this
//        userPresenter.userInfoView = this
        userPresenter.nickNameView = this
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment2_my, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        load()
        setting.setOnClickListener(this)
        user_avatar.setOnClickListener(this)
        withdraw_btn.setOnClickListener(this)
        my_lottery.setOnClickListener(this)
        bean_layout.setOnClickListener(this)
        msg_center.setOnClickListener(this)
        my_tipsbook.setOnClickListener(this)


        //长按头像
        user_avatar.setOnLongClickListener {
            val deviceId = TokenManager.getDeviceId()
                    ?: AppHelper.getDeviceIdWithoutGuarantee(requireActivity())
            if (tv_simple == null)
                viewStub.inflate()

            tv_simple.text = getString(R.string.your_deviceid, ChannelUtil.getChannel(), deviceId)

            tv_simple.setOnClickListener {
                context?.copy(deviceId)
                Toaster.message("已复制设备号到剪切板")
            }

            true
        }
    }

    fun load() {
        userPresenter.loadUserInfoEx(::onUserInfoLoad, ::onError)
        activityPresenter.loadBanner(::onBannerLoad, ::onError)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUnReadMessage(e: UnReadMessageEvent) {

    }

    @Throttle(time = 1)
    override fun onClick(v: View) {
        when (v.id) {
            R.id.setting -> startActivity(Intent(requireActivity(), AccountSettingActivity::class.java))
//            R.id.user_avatar -> quickStartActivity(ChangeAvatarActivity::class.java)/*popAvatarChoiceSheet()*/

            R.id.withdraw_btn -> {
                quickStartActivity(WithDrawActivity2::class.java)
//                else showBindPhoneAlertDialog()
            }

            R.id.msg_center -> quickStartActivity(WithDrawRecordActivity::class.java)
            R.id.bean_layout -> quickStartActivity(TradingMarketActivity::class.java)
            R.id.lottery_btn -> {
                if (phoneBind)
                    WebViewActivity.loadImmersive(requireActivity(), Store.URL_LOTTERY)
                else showBindPhoneAlertDialog()
            }
            R.id.my_lottery -> quickStartActivity(GameCenterActivity::class.java)
            R.id.feedBack -> quickStartActivity(FeedBack2Activity::class.java)
            R.id.my_detail -> startActivity(Intent(requireActivity(), DetailsActivity::class.java))
            R.id.my_rank -> WebViewActivity.load(requireActivity(), Store.URL_RANK_AGREEMENT)
            R.id.my_friend -> {
                contactService()
            }
            R.id.my_tipsbook -> {
                WebViewActivity.load(requireActivity(), Store.URL_TIPS)
            }
            R.id.my_activity -> WebViewActivity.load(requireActivity(), Store.URL_ACTIVITY)
            R.id.username -> alertDialog = NickNameEditorDialog.create(requireActivity(), this@MyFragment).also { it.show() }
        }
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden.not()) {
            load()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogin(event: LoginEvent) {
        load()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAvatarChange(event: AvatarChangeEvent) {
        userPresenter.loadUserInfoEx(::onUserInfoLoad, ::onError)
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)


        shareVieModel.deviceIdChange.observe(viewLifecycleOwner, Observer {
            tv_simple?.text = getString(R.string.your_deviceid, ChannelUtil.getChannel(), TokenManager.getDeviceId())
        })

        shareVieModel.beanCount.observe(viewLifecycleOwner, Observer {
            Log.i(TAG, "onActivityCreated: bean count $it")
        })

        shareVieModel.diamondCount.observe(viewLifecycleOwner, Observer {
            Log.i(TAG, "onActivityCreated: $ count $it")
        })

    }


    var banners: List<Banner>? = null
    fun onBannerLoad(banners: List<Banner>) {

        this.banners = banners

        banner_viewPager.adapter = SimpleNetWorkLoopingPagerAdapter(requireContext(), banners.map { it.img }, true, ::onBannerClick)
    }

    fun onBannerClick(pos: Int) {

        this.banners?.get(pos)?.apply {
            WebViewActivity.load(requireContext(), url)
        }

    }

    @SuppressLint("SetTextI18n")
    fun onUserInfoLoad(user: IndexData) {
        val userInfo = user.user_info
        if (view == null) return

        username.setText(userInfo.username)
        userId.setText("ID:${userInfo.userid}")
        Glide.with(requireContext())
                .load(userInfo.avatar)
                .into(user_avatar)

        if (TextUtils.isEmpty(user.user_info.inviterid).not())
            inverter_id.text = "ID:${user.user_info.inviterid}"
        cash_num.setText(userInfo.gold_z)
    }

    lateinit var alertDialog: AlertDialog


    @NetWorkRequired
    private fun checkInviteMan() {

        userPresenter.checkInviteMan({

            WebViewActivity.load(requireActivity(), Store.URL_INVITE_MAN)
        }, {
            if (it is ExpiredException) onAuthExpired()
            else {
                AlertDialog.Builder(requireActivity())
                        .setTitle("邀请达人")
                        .setMessage("您现在还不是达人，无法查看达人信息。是否成为达人？")
                        .setPositiveButton("成为达人") { dialog, which ->
                            WebViewActivity.load(requireActivity(), Store.URL_INVITE_MAN_INDEX)
                            dialog.dismiss()

                        }
                        .setNegativeButton("放弃") { dialog, which ->

                            dialog.dismiss()
                        }
                        .create()
                        .show()
            }
        })
    }

    @NetWorkRequired
    private fun contactService() {
        WebViewActivity.load(requireContext(), Store.Service)
    }


    private fun showBindPhoneAlertDialog() {

        SimpleDialogBuilder()
                .title("提示")
                .titleTextColor(R.color.colorPrimary)
                .buttonText("我知道了")
                .content("请先绑定手机号")
                .onButtonClick(View.OnClickListener {
                    quickStartActivity(BindPhoneActivity::class.java)
                })
                .build(requireContext())
                .show()
    }

    /**
     * 输入了昵称
     */
    override fun onPromote(pwd: String) {
        userPresenter.setNickName(pwd)
    }

    private val REQUEST_ALBUM = 0x00
    private var dialog: BottomSheetDialog? = null

    /**
     * 更换头像弹窗
     */
    private fun popAvatarChoiceSheet() {
        dialog = BottomSheetDialog(requireActivity())
        val view = layoutInflater.inflate(R.layout.avatar_change_dialog, null)
        dialog?.setContentView(view)
        view.findViewById<View>(R.id.uploadAvatar).setOnClickListener {
            val albumIntent = Intent(Intent.ACTION_PICK)
            albumIntent.data = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            startActivityForResult(albumIntent, REQUEST_ALBUM)
        }
        view.findViewById<View>(R.id.cancel).setOnClickListener { dialog?.dismiss() }
//        view.findViewById<View>(R.id.changeDefaultAvatar).setOnClickListener {}
        (view.parent as ViewGroup).setBackgroundResource(android.R.color.transparent)
        dialog?.show()

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && data != null)
            if (requestCode == REQUEST_ALBUM)//获取到图片，然后请求裁切
                CropImageActivity.start(this, data.data!!)
            else if (requestCode == CropImageActivity.REQUEST_CROP) {
                //裁切之后的图片uri
                user_avatar.setImageURI(data.data)
                userPresenter.uploadAvatar(File(data.data!!.path))
                dialog?.dismiss()
            } else dialog?.dismiss()
    }

    override fun onAvatarChange(avatarUrl: String) {
        Glide.with(requireActivity())
                .load(avatarUrl)
                .into(user_avatar)
        EventBus.getDefault().post(AvatarEvent(avatarUrl))
    }

    @Subscribe
    fun onLogout(e: LogoutEvent) {
        username.text = "未登录"
        userId.text = "---"
        Glide.with(requireActivity()).load(R.drawable.xg_touxiang).into(user_avatar)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDiamondChange(event: DiamondChangeEvent) {
        diamondNumber?.text = String.format("%,d", event.newCount.toInt())
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPhoneBind(e: PhoneBindEvent) {
        phoneBind = true
    }

    /**
     * 及时更新用户等级等信息
     */
    override fun onResume() {
        super.onResume()
        if (TokenManager.isLoginValid())
            load()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}


